package openbang.account.service.impl;

import java.io.IOException;
import java.util.Collection;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openbang.account.service.entity.VerifyRecord;
import openbang.account.service.util.PMF;
import openbang.account.service.util.SessionHelper;
import openbang.account.service.vo.BusinessEnum;
import openbang.account.service.vo.VerifyStatusEnum;

/**
 * 普通的Servlet
 * 用户申请了找回密码后,单击URL的响应处理 -- 判断用户是否可以设置密码
 * 当用户录入了新密码，由 AccountService服务来处理密码的更改。
 * @author aibozeng
 *
 */

@SuppressWarnings("serial")
public class SetupPwdServlet extends HttpServlet{
	private static final Logger log = Logger.getLogger(SetupPwdServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
		String email = req.getParameter("email");
		String uuid = req.getParameter("id");
		log.info("come in SetupPwdServlet email="+email+",id="+uuid);
		if(email==null ||uuid==null||email.length()<=0||uuid.length()<=0){			
			SessionHelper.forwardToErrorPage(BusinessEnum.FIND_PWD.getDesc(),"参数为空","从邮件里重新拷贝URL到浏览器地址栏", req, resp);
			return;
		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(VerifyRecord.class);
		q.setFilter("status=="+VerifyStatusEnum.PENDING.getCode()+"&& busiType == "+BusinessEnum.FIND_PWD.getCode()+" && email == email_address && verifyCode== verify_code ");
		q.setOrdering("applyTime desc");
		q.setRange(0,1); //找出最新
		q.declareParameters("java.lang.String email_address , java.lang.String verify_code");
		Collection<VerifyRecord> users = (Collection<VerifyRecord>) q.execute(email, uuid);
		VerifyRecord findPwdRecord = null;
		if(users!=null && users.size()>0){
			findPwdRecord = users.iterator().next();
		}
		else{
			pm.close();
			SessionHelper.forwardToErrorPage(BusinessEnum.FIND_PWD.getDesc(),"申请记录找不到","请重新申请找回密码", req, resp);
			return;			
		}
		pm.close();
		try {
			req.setAttribute("applyId", findPwdRecord.getId());
			req.setAttribute("email", findPwdRecord.getEmail());
			req.getRequestDispatcher("/accountSetupPwd.jsp").forward(req, resp);
		} catch (ServletException e) {
		}
		return;
    }
	

}
